<template>
  <el-dialog title="连接设备" :model-value="visible" width="1000px" append-to-body @close="handleClose">
    <div class="device-header">
      <el-form :model="queryParams" :inline="true">
        <el-form-item label="设备名称">
          <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="设备类型">
          <el-select v-model="queryParams.deviceType" placeholder="请选择设备类型" clearable style="width: 150px">
            <el-option label="传感器" value="sensor" />
            <el-option label="执行器" value="actuator" />
            <el-option label="控制器" value="controller" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="连接状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="在线" value="online" />
            <el-option label="离线" value="offline" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <el-table :data="deviceList" v-loading="loading" border>
      <el-table-column prop="deviceId" label="设备ID" width="120" />
      <el-table-column prop="deviceName" label="设备名称" width="150" />
      <el-table-column prop="deviceType" label="设备类型" width="100">
        <template #default="{ row }">
          <el-tag :type="getDeviceTypeTagType(row.deviceType)">{{ getDeviceTypeText(row.deviceType) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="manufacturer" label="制造商" width="120" />
      <el-table-column prop="model" label="型号" width="120" />
      <el-table-column prop="status" label="连接状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 'online' ? 'success' : 'danger'">
            {{ row.status === 'online' ? '在线' : '离线' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="lastHeartbeat" label="最后心跳" width="160" />
      <el-table-column prop="connectTime" label="连接时间" width="160" />
      <el-table-column label="操作" width="240" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link size="small" @click="handleViewDevice(row)">详情</el-button>
          <el-button type="danger" link size="small" @click="handleDisconnect(row)">断开</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleRefresh">刷新</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// Props
interface Props {
  visible: boolean
  gatewayId?: string
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  gatewayId: ''
})

// Emits
const emit = defineEmits(['update:visible', 'view-device', 'disconnect'])

// 响应式数据
const loading = ref(false)
const total = ref(0)
const deviceList = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  deviceName: '',
  deviceType: '',
  status: '',
  gatewayId: ''
})

// 监听网关ID变化
watch(() => props.gatewayId, (newId) => {
  if (newId) {
    queryParams.gatewayId = newId
    getDeviceList()
  }
}, { immediate: true })

// 监听对话框显示状态
watch(() => props.visible, (visible) => {
  if (visible && props.gatewayId) {
    getDeviceList()
  }
})

// 获取设备列表
const getDeviceList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    const mockData = {
      total: 25,
      rows: [
        {
          deviceId: 'DEV001',
          deviceName: '温度传感器01',
          deviceType: 'sensor',
          manufacturer: '华为',
          model: 'HW-T100',
          status: 'online',
          lastHeartbeat: '2024-01-15 14:30:25',
          connectTime: '2024-01-15 08:00:00'
        },
        {
          deviceId: 'DEV002',
          deviceName: '湿度传感器01',
          deviceType: 'sensor',
          manufacturer: '小米',
          model: 'MI-H200',
          status: 'offline',
          lastHeartbeat: '2024-01-15 12:15:30',
          connectTime: '2024-01-15 08:00:00'
        },
        {
          deviceId: 'DEV003',
          deviceName: '智能开关01',
          deviceType: 'actuator',
          manufacturer: '海康威视',
          model: 'HIK-S300',
          status: 'online',
          lastHeartbeat: '2024-01-15 14:29:45',
          connectTime: '2024-01-15 08:00:00'
        }
      ]
    }
    
    deviceList.value = mockData.rows
    total.value = mockData.total
  } catch (error) {
    ElMessage.error('获取设备列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1
  getDeviceList()
}

// 重置
const resetQuery = () => {
  queryParams.deviceName = ''
  queryParams.deviceType = ''
  queryParams.status = ''
  queryParams.pageNum = 1
  getDeviceList()
}

// 查看设备详情
const handleViewDevice = (row: any) => {
  emit('view-device', row)
}

// 断开设备连接
const handleDisconnect = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确认断开设备 "${row.deviceName}" 的连接吗？`,
      '系统提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟API调用
    ElMessage.success('设备连接已断开')
    emit('disconnect', row)
    getDeviceList()
  } catch {
    // 用户取消操作
  }
}

// 刷新
const handleRefresh = () => {
  getDeviceList()
}

// 分页大小变更
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  getDeviceList()
}

// 当前页变更
const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val
  getDeviceList()
}

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false)
}

// 获取设备类型标签类型
const getDeviceTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    sensor: 'primary',
    actuator: 'success',
    controller: 'warning',
    other: 'info'
  }
  return typeMap[type] || 'info'
}

// 获取设备类型文本
const getDeviceTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    sensor: '传感器',
    actuator: '执行器',
    controller: '控制器',
    other: '其他'
  }
  return typeMap[type] || '未知'
}
</script>

<style scoped>
.device-header {
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 16px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}
</style>